//
//  FLLSearchViewController.m
//  FLLGodOfCooking
//
//  Created by LL.F on 16/9/12.
//  Copyright © 2016年 LL.F. All rights reserved.
//

#import "FLLSearchViewController.h"
#import "ZWYNetTool.h"
#import "FLLMacro.h"
#import "FLLFindViewController.h"
#import "FLLSearchModel.h"
#import "SearchData.h"
#import "SearchSecData.h"
@interface FLLSearchViewController ()<UISearchResultsUpdating, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>
@property (nonatomic, strong) UISearchController *search;
@property (nonatomic, strong) NSMutableArray<SearchSecData *> *dataSource;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSString *keyText;
@property (nonatomic, strong) FLLSearchModel *fllSearchModel;
@end

@implementation FLLSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
      
    [self creatTableView];
    [self createSearchController];
    
    
}

- (void)createPOSTRequest
{
    
    if (self.dataSource.count != 0) {
        [self.dataSource removeAllObjects];
        //tableView要刷新一下
        [self.tableView reloadData];
    }
    //重新请求数据
    NSString *bodyString = [NSString stringWithFormat:@"methodName=SearchKeyword&keyword=%@&version=4.40&", _keyText];
    [ZWYNetTool POST:@"http://api.izhangchu.com" andBody:bodyString andBodyStyle:ZWYBodyString andHeader:@{@"Content-Type":@"application/x-www-form-urlencoded; charset=utf-8"} andResponse:ZWYJSON andSuccessBlock:^(id result) {
        
        self.fllSearchModel = [FLLSearchModel modelWithDic:result];
        self.dataSource = (NSMutableArray *)self.fllSearchModel.data.data;
        
        [self.tableView reloadData];
        
    } andFailureBlock:^(NSError *error) {
        
    }];
    
    
    
}

- (void)creatTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    
    [self.view addSubview:_tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *string = self.dataSource[indexPath.row].text;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.textLabel.text = string;
    
    
    /** 关键字高亮*/
    NSString *highLightString = self.search.searchBar.text;
    NSMutableAttributedString *attribut = [[NSMutableAttributedString alloc]initWithString:string];
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:17], NSForegroundColorAttributeName : FLLOrangeColor};
    NSRange range = [string rangeOfString:highLightString];
    [attribut addAttributes:dic range:range];
    cell.textLabel.attributedText = attribut;
    
    
    
    
    return cell;
    
}


- (void)createSearchController
{
    /** 初始化 */
    self.search = [[UISearchController alloc]initWithSearchResultsController:nil];
    /** 设置代理人 */
    self.search.searchResultsUpdater = self;
    /** 搜索期间可以拖动tableView*/
    self.search.dimsBackgroundDuringPresentation = NO;
    /** 搜索期间不隐藏导航条*/
    self.search.hidesNavigationBarDuringPresentation = NO;
    
    self.search.searchBar.frame = CGRectMake(0, 20, 200, 30);
    self.search.searchBar.delegate = self;
    
//    [self.view addSubview:_search.searchBar];
    
    self.navigationItem.titleView = _search.searchBar;
    
    self.search.searchBar.placeholder = @"请输入搜索的内容";
    
}

#pragma mark -- searchBarController的代理方法
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    // 让取消按钮提前显示出来
    [self.search.searchBar setShowsCancelButton:YES animated:NO];
    self.search.searchBar.tintColor = FLLOrangeColor;
    
    // 修改默认取消按钮
    [self.search.searchBar.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull view, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [view.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if ([obj isKindOfClass:NSClassFromString(@"UIButton")]) {
                
                UIButton *button = obj;
                [button setTitle:@"取消" forState:UIControlStateNormal];
                
            }
            
        }];
        
    }];

    self.keyText = searchController.searchBar.text;
    [self createPOSTRequest];
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    FLLFindViewController *findVC = [[FLLFindViewController alloc] init];
    findVC.keyString = self.dataSource[indexPath.row].text;
    [self.navigationController pushViewController:findVC animated:YES];
    
}
// 点击搜索后显示结果
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{

    FLLFindViewController *findVC = [[FLLFindViewController alloc] init];
    findVC.keyString = self.keyText;
    [self.navigationController pushViewController:findVC animated:YES];
    
}
// 点击取消按钮返回
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{

//    [self.search removeFromParentViewController];
//
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
